package cn.slipi.admin.config;

import cn.slipi.admin.common.handler.convert.JacksonHttpMessageConverter;
import cn.slipi.admin.common.handler.exception.DefaultExceptionHandler;
import cn.slipi.admin.common.handler.exception.ServiceExceptionHandler;
import cn.slipi.admin.common.interceptor.GateInterceptor;
import cn.slipi.admin.common.interceptor.IllegalInterceptor;
import cn.slipi.admin.constants.AdminConstants;
import cn.slipi.admin.filter.ContextFilter;
import cn.slipi.admin.interceptor.AuthInterceptor;
import cn.slipi.admin.interceptor.PermissionInterceptor;
import org.apache.commons.codec.Charsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

/**
 * 应用配置
 *
 * @author lee
 * @date 2019-03-17
 * @since 1.0.0
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    private AuthInterceptor authInterceptor;

    @Autowired
    private GateInterceptor gateInterceptor;

    @Autowired
    private IllegalInterceptor illegalInterceptor;

    @Autowired
    private PermissionInterceptor permissionInterceptor;

    @Autowired
    private ServiceExceptionHandler serviceExceptionHandler;

    @Autowired
    private DefaultExceptionHandler defaultExceptionHandler;

    private final static String PATH_API_PATTERN = "/" + AdminConstants.CAR_API_PREFIX + "/**";
    private final static String PATH_ALL_PATTERN = "/**";

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(gateInterceptor).addPathPatterns(PATH_API_PATTERN);
        registry.addInterceptor(authInterceptor).addPathPatterns(PATH_ALL_PATTERN);
        registry.addInterceptor(illegalInterceptor).addPathPatterns(PATH_ALL_PATTERN);
        registry.addInterceptor(permissionInterceptor).addPathPatterns(PATH_API_PATTERN);
        super.addInterceptors(registry);
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(PATH_ALL_PATTERN);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        JacksonHttpMessageConverter converter = new JacksonHttpMessageConverter();
        converters.add(converter);
        for (int i = 0; i < converters.size(); i++) {
            if (converters.get(i) instanceof StringHttpMessageConverter) {
                StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charsets.UTF_8);
                stringHttpMessageConverter.setWriteAcceptCharset(false);
                converters.set(i, stringHttpMessageConverter);
                break;
            }
        }
    }

    @Bean
    public FilterRegistrationBean<ContextFilter> filterRegistrationBean() {
        FilterRegistrationBean<ContextFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new ContextFilter());
        bean.addUrlPatterns("/*");
        bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
        exceptionResolvers.add(serviceExceptionHandler);
        exceptionResolvers.add(defaultExceptionHandler);
    }

    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        source.registerCorsConfiguration("/**", config);
        final FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

}
